package org.jow.worldsrv;

import java.io.IOException;

import org.jow.core.Record;
import org.jow.core.InputStream;
import org.jow.core.OutputStream;
import org.jow.core.interfaces.ISerilizable;
import org.jow.worldsrv.character.${character?lower_case}.${character}Object;
<#list methodsList as m>
<#list m.importPackages as package>
import ${package};
</#list>
<#list m.entityPackages as epackage>
import ${epackage};
</#list>
</#list>

/**
 * @author gaopan
 *
 * 管理${character}Object的模块
 */
public class ${character}Module implements ISerilizable {
		
	public static enum EModType {
	<#list methodsList as m>
		${m.className},
	</#list>
		;
	}
	
	private Module${character}Base[] modules = new Module${character}Base[EModType.values().length];
	
	public ${character}Module() {
	<#list methodsList as m>
		modules[EModType.${m.className}.ordinal()] = new ${m.className}();
	</#list>
	}
	
	/**
	 * 设置
	 * 
	 * @param ${character?uncap_first}Obj
	 */
	public void set${character}Object(${character}Object ${character?uncap_first}Obj) {
		for (Module${character}Base module : modules) {
			if(module != null) {
				module.set${character}Obj(${character?uncap_first}Obj);
			}
		}
	}
	
	/**
	 * 初始化
	 * 
	 * @param isLogin
	 */
	public void initData(boolean isLogin) {
		for (Module${character}Base module : modules) {
			if(module != null) {
				module.initData(isLogin);
			}
		}
	}
	
	/**
	 * 心跳
	 * @param now
	 */
	public void pulse(long now){
		for (Module${character}Base module : modules) {
			if(module != null) {
				module.pulse(now);
			}
		}
	}
	
	/**
	 * 添加一个组件
	 * 
	 * @param key
	 * @param module
	 */
	public void addModule(EModType type, Module${character}Base module) {
		this.modules[type.ordinal()] = module;
	}

	/**
	 * 删除一个组件
	 * 
	 * @param key
	 */
	public void delModule(EModType type) {
		this.modules[type.ordinal()] = null;
	}

	<#list methodsList as m>
	public ${m.className} get${m.className}() {
		return (${m.className}) modules[EModType.${m.className}.ordinal()];
	}
	
	</#list>

	@Override
	public void writeTo(OutputStream out) throws IOException {
		out.write(modules);
	}

	@Override
	public void readFrom(InputStream in) throws IOException {
		Object[] objs = in.read();
		for(int i = 0; i < objs.length; ++i) {
			modules[i] = (Module${character}Base)objs[i];
		}
	}
		
	/**
	 * 处理外来record（通常来自跨服）
	 * @param record
	 * @return
	 */
	public boolean processRecord(Record record) {
		boolean processed = true;
		switch (record.getTableName()) {
	<#list methodsList as m>
		<#list m.entityClass as ec>
		case ${ec}.tableName:
			get${m.className}().processRecord(record);
			break;
		</#list>
	</#list>
		default:
			processed = false;
		}
		return processed;
	}
	
}
